package com.tydic.controller;

import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

@RequestMapping("/test")
@RestController
public class TestController {

    @GetMapping("/httpTest")
    public Map<String, Object> httpTest() {
        Map<String, Object> map = new HashMap<>();
        map.put("msg", "测试byte数组数据传输");
        String str = "这是一个字符串";
        map.put("bytes", str.getBytes());
        return map;
    }

    @ApiOperation("下载附件")
    @GetMapping("/downloadFile")
    public void downloadFile(HttpServletRequest request, HttpServletResponse response) {
        String fileUrl = "C:\\Users\\wangkl\\Desktop\\ceshi\\5张表\\TEST_报警复核.xlsx";
        InputStream ins = null;
        OutputStream outStream = null;
        try {
            response.reset();//清空response缓存信息
            //下载方式控制文件头信息
            response.setCharacterEncoding("UTF-8");
            //设置响应类型
            response.setContentType("application/octet-stream;charset=utf-8");

            File file = new File(fileUrl);
            if (file.exists()) {
                //返回浏览器类型
                String browser = request.getHeader("User-Agent");
                String filename = URLEncoder.encode(file.getName(), "UTF-8");
                if (browser.toLowerCase().contains("chrome") || browser.toLowerCase().contains("firefox")) {
                    filename = new String(file.getName().getBytes("UTF-8"), "ISO8859-1");
                }
                response.addHeader("Content-disposition", "attachment;filename=" + filename);

                ins = new FileInputStream(file);
                outStream = response.getOutputStream();
                byte[] bytes = new byte[1024];

                int temp = 0;
                while ((temp = ins.read(bytes)) != -1) {
                    outStream.write(bytes, 0, temp);
                }
                outStream.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ins != null) {
                try {
                    ins.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outStream != null) {
                try {
                    outStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
